// pages/tool/card/make1/Template/Template.js
let app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        progress: [1, 0, 0, 0,],   // 0默认  1制作中  2已完成
        currentTitle: 0,
        cardtypeValue: 99,
        currentCardImg: 0,
        cardinfo:'',

        makeType: [],
        maketypeValue: 99,
        nowCardInfo:{},
        navScrollLeftIconcard:0
    },


    myinfo: function (cd) {
        app.func.getPromise('/my/info')
            .then(([code, res]) => {
                cd(code, res);
            })
    },
    checkUserAuth:function(res){
        if(res.data.customers.length == 0){
            wx.switchTab({
                url:'/pages/about/about'
            })
        }
    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.myinfo((code, res) => {
            this.checkUserAuth(res);

            this.setData({
                userid:res.data.userid,
            });
            const forData = [
                {
                    data:res.data.customers[0].status != 3 && res.data.customers[0].card_audit != 3,
                    value:'您当前未完成企业认证和卡券认证，无法提交印刷或生成电子券！现在邀请您体验一下制券，是否去体验？'
                },
                {
                    data:res.data.customers[0].status != 3,
                    value:'您当前未完成企业认证，无法提交印刷或生成电子券！现在邀请您体验一下制券，是否去体验？'
                },
                {
                    data:res.data.customers[0].status != 3,
                    value:'您当前未完成卡券认证，无法提交印刷或生成电子券！现在邀请您体验一下制券，是否去体验？'
                },
            ];
            for(let i=0; i<forData.length; i++){
                if(forData[i].data){
                    this.setData({
                        tiptext:forData[i].value,
                        page_url:'template',
                        popup: true,
                        auth_url:res.data.customers[0].auth_url,
                    });
                    return;
                }
            }


        });

        app.func.getPromise('/card/festivalcard')
            .then(([code,res])=>{
                res.data.push({
                    themeId:-1,
                    name:'自定义'
                });
                 this.setData({
                         cardinfo:res.data
                     },()=>{
                     this.makeTypeFilter(0,0);
                 });
            })
    },


    cardIconCenterPre(index) {
        let that = this;
        wx.createSelectorQuery().selectAll(".tem-swipei-pot2").fields({size: true}, function (res) {
            let result = res.reduce( (sum,item,index1)=> index1<index ? sum+item.width+10 : sum,0);
            that.cardIconCenter(result, index);
        }).exec();
    },
    cardIconCenter(left,index){
        let that = this;
        wx.createSelectorQuery().select("#cardicon-" + index).fields({size: true}, function (res) {
            let result = left + res.width / 2;
            wx.createSelectorQuery().select(".cardicon").fields({size: true, rect: true}, function (res) {
                that.setData({navScrollLeftIconcard: result - res.width / 2})
            }).exec();
        }).exec();
    },
    smallImg: function (e) {
        let index = e.currentTarget.dataset.index;
        this.setData({currentSwiper: index});
        this.cardIconCenter(e.currentTarget.offsetLeft,index);
    },



    //点击元素 自动居中
    autoCenter: function (json) {
        var that = this;
        let e = json.currente;
        let index = e.currentTarget.dataset.index;
        wx.createSelectorQuery().select(json.id).fields({size: true}, function (res) {
            let itemwidth = res.width;
            let left = e.currentTarget.offsetLeft;
            left = left + itemwidth / 2;
            wx.createSelectorQuery().select(json.class).fields({size: true, rect: true}, function (res) {
                let move = left - res.width / 2;
                if (json.type == 0) {
                    that.setData({
                        currentTitle: index, navScrollLeft: move,
                        currentCardImg:0,currentSwiper:0,
                        maketypeValue: 99,navScrollLeftIconcard:0
                    },()=>{
                        that.makeTypeFilter(index,0);
                    });
                } else {
                    let nowCardInfo={
                        folds:e.currentTarget.dataset.folds,
                        products:e.currentTarget.dataset.products,
                        name:e.currentTarget.dataset.name,
                        id:e.currentTarget.dataset.id,
                        brand_id:e.currentTarget.dataset.brand_id,
                    };
                    that.setData({
                        cardtypeValue: index, navScrollLeft1: move,nowCardInfo:nowCardInfo
                    });
                }
            }).exec();
        }).exec();
    },


    //制作类型筛选
    makeTypeFilter: function(currentTitle,currentCardImg){
         let makeType = [
             {name:'券',type:1},
             {name:'册',type:2},
             {name:'卡',type:3},
         ];
         let items = [];
         let data = this.data.cardinfo[currentTitle].themePic[currentCardImg].cardtype;
         for(let i =0; i<makeType.length; i++){
                for(let j=0; j<data.length; j++){
                      if(data[j].type == makeType[i].type){
                           items.push(makeType[i]);
                           break;
                      }
                }
         }
         this.setData({ makeType:items });
    },

    tipsDefineMake: function(e){
        wx.showModal({
            title: '提示',
            content: '此功能仅限电脑端上传自定义券样（网址：www.dianlinet.com）',
            showCancel: false,
        });
    },
    //选择主题
    selected_title: function (e) {
        if(e.currentTarget.dataset.item.themeId === -1){
            this.tipsDefineMake(e);
            return;
        }
        let id = "#title-" + e.currentTarget.dataset.index;
        let json = {currente: e, type: 0, id: id, class: '.tem-title2'};
        this.autoCenter(json);
    },
    //选择券样
    swiperFunc: function (e) {
        let currentCardImg = e.detail.current;
        let currentTitle = this.data.currentTitle;
        this.setData({
            currentCardImg: currentCardImg,
            maketypeValue: 99,
        },()=>{
            this.makeTypeFilter(currentTitle,currentCardImg);
            this.cardIconCenterPre(currentCardImg);
        });
    },


    //制作类型
    makeType: function (e) {
        let type = e.currentTarget.dataset.type;
        this.setData({
            maketypeValue: type,
            cardtypeValue:99,
        });
    },

    //选择兑换方式
    cardType: function (e) {
        let id = "#choose-" + e.currentTarget.dataset.index;
        let json = {currente: e, type: 1, id: id, class: '.template-scoll-view'};
        this.autoCenter(json);
    },



    next: function (e) {
        let userid = this.data.userid;
        let currentTitle = this.data.currentTitle;
        let maketypeValue = this.data.maketypeValue;
        let cardtypeValue = this.data.cardtypeValue;
        if(currentTitle !=99 && maketypeValue!=99 && cardtypeValue!=99 ){
            let data = this.data.nowCardInfo;
            let count = data['products'];
            let templateid = data['id'];
            let folders = data['folds'];
            let name = data['name'];
            let brand_id = data['brand_id'];
            wx.navigateTo({
                url: "/tools/pages/tool/card/make1/redirect/redirect",
                events: {},
                success(res) {
                    res.eventChannel.emit('definition', {
                        type: maketypeValue,         //1券 2册  3卡
                        count: count,        //数量
                        templateid: templateid,   //模版id
                        folders: folders,      //折数
                        name: name,      //券样名称
                        brand_id:brand_id //授权品牌id
                    });
                },
                complete(res) {
                    wx.reportAnalytics('ontemplate', {
                        userid: userid,
                    })
                }
            })
        }else{
            app.func.toastPromise('请完善主题信息')
        }


    },



    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
